package com.lin.mybatisdubbomysql.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.lin.mybatisdubbomysql.enums.DateBaseEnum;
import com.lin.mybatisdubbomysql.extend.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 九分石人
 */
@Configuration
@MapperScan(basePackages = "com.lin.mybatisdubbomysql.dal.mapper",sqlSessionFactoryRef = "sqlSessionFactory")
public class DBConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasourceone")
    public DataSource dataSourceOne() {
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasourcetwo")
    public DataSource dataSourceTwo() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource dataSourceOne,DataSource dataSourceTwo){
        Map<Object, Object> targetDataSources = new HashMap<>(8);
        targetDataSources.put(DateBaseEnum.DataBaseOne.getValue(),dataSourceOne);
        targetDataSources.put(DateBaseEnum.DataBaseTwo.getValue(), dataSourceTwo);
        return new DynamicDataSource(dataSourceOne, targetDataSources);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource dynamicDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource);
        return sqlSessionFactoryBean.getObject();
    }

}
